/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader.internal;

import lombok.NoArgsConstructor;
import org.apache.commons.lang3.Validate;
import org.jrose.api.annotation.common.ConfigurationLocation;
import org.jrose.api.annotation.remote.ExposeHttpService;
import org.jrose.api.common.IterableFilter;
import org.jrose.core.util.CollectionUtils;
import org.jrose.core.util.ConversionUtils;
import org.jrose.entity.config.Lineup;
import org.jrose.entity.config.LineupCoordinate;
import org.jrose.entity.data.Team;
import org.jrose.entity.data.TeamLineup;
import org.jrose.service.loader.AbstractStandardConfigurationLoader;
import org.jrose.service.loader.LineupLoader;
import org.w3c.dom.Element;

import javax.inject.Named;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static org.jrose.core.util.XMLUtils.getChildElementText;
import static org.jrose.core.util.XMLUtils.getChildElements;
import static org.jrose.core.util.XMLUtils.getSingleChildElement;

/**
 * Default {@link LineupLoader} implementation.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-25 01:52
 */
@Named
@NoArgsConstructor
@ConfigurationLocation("/config/lineup-configuration.xml")
@AbstractStandardConfigurationLoader.StandardConfiguration("lineup")
@ExposeHttpService(name = "/lineupLoader", serviceInterface = LineupLoader.class)
public class LineupLoaderImpl extends AbstractStandardConfigurationLoader<Lineup> implements LineupLoader {
    private final Map<Integer, Lineup> lineups = new HashMap<>();
    private final List<Lineup> initialAvailableLineups = new LinkedList<>();
    private final List<Lineup> monsterAvailableLineups = new LinkedList<>();

    @Override
    protected Lineup parseElement(Element element) {
        String id = getChildElementText(element, "id");
        String name = getChildElementText(element, "name");
        String description = getChildElementText(element, "description");
        boolean initialAvailable = getSingleChildElement(element, "initial-available") != null;
        boolean monsterAvailable = getSingleChildElement(element, "monster-available") != null;

        Lineup lineup = new Lineup();
        lineup.setId(ConversionUtils.toInt(id));
        lineup.setName(name);
        lineup.setDescription(description);
        lineup.setInitialAvailable(initialAvailable);
        lineup.setMonsterAvailable(monsterAvailable);
        lineup.setCoordinates(new LinkedHashMap<Integer, LineupCoordinate>());

        List<Element> coordinateElements = getChildElements(getSingleChildElement(element, "coordinates"), "coordinate");
        for (Element coordinateElement : coordinateElements) {
            LineupCoordinate lineupCoordinate = new LineupCoordinate();
            lineupCoordinate.setIndex(ConversionUtils.toInt(coordinateElement.getAttribute("index")));
            lineupCoordinate.setX(ConversionUtils.toInt(coordinateElement.getAttribute("x")));
            lineupCoordinate.setY(ConversionUtils.toInt(coordinateElement.getAttribute("y")));
            Validate.isTrue(!lineup.getCoordinates().containsKey(lineupCoordinate.getIndex()), "Duplicated index found");
            lineup.getCoordinates().put(lineupCoordinate.getIndex(), lineupCoordinate);
        }
        return lineup;
    }

    @Override
    protected void processConfigurations(List<Lineup> configurations) {
        for (Lineup lineup : configurations) {
            lineups.put(lineup.getId(), lineup);
            if (lineup.isInitialAvailable()) {
                initialAvailableLineups.add(lineup);
            }
            if (lineup.isMonsterAvailable()) {
                monsterAvailableLineups.add(lineup);
            }
        }
    }

    @Override
    public Lineup load(int id) {
        initializeLoader();
        return lineups.get(id);
    }

    @Override
    public List<Lineup> load() {
        initializeLoader();
        return Collections.unmodifiableList(new LinkedList<>(lineups.values()));
    }

    @Override
    public List<Lineup> loadInitialAvailableLineups() {
        initializeLoader();
        return Collections.unmodifiableList(initialAvailableLineups);
    }

    @Override
    public List<Lineup> loadMonsterAvailableLineups() {
        initializeLoader();
        return Collections.unmodifiableList(monsterAvailableLineups);
    }

    @Override
    public List<Lineup> loadTeamLineups(Team team) {
        if (team == null) {
            return Collections.emptyList();
        }
        List<Lineup> lineups = new LinkedList<>();
        List<TeamLineup> teamLineups = teamLineupPersistence.findByTeamId(team.getId());
        for (TeamLineup teamLineup : teamLineups) {
            CollectionUtils.addNonNullElement(lineups, load(teamLineup.getLineupId()));
        }
        return lineups;
    }

    @Override
    public Lineup loadTeamActiveLineup(Team team) {
        if (team == null) {
            return null;
        }
        List<TeamLineup> teamLineups = teamLineupPersistence.findByTeamId(team.getId());
        teamLineups = CollectionUtils.filterIterable(teamLineups, new IterableFilter<TeamLineup>() {
            @Override
            public boolean accept(TeamLineup element) {
                return element.isActiveLineup();
            }
        });
        TeamLineup activeTeamLineup = CollectionUtils.firstElement(teamLineups);
        if (activeTeamLineup == null) {
            return null;
        }
        return load(activeTeamLineup.getLineupId());
    }
}
